# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

myStartsWith <- function(str, prefix){
    substring(str, 1, nchar(prefix)) == prefix
}

library(optparse)
library(ropls)
library(magrittr)
library(RColorBrewer)
library(scales)
library(tidyverse)

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--mc", default = "meta_color.txt", type = "character", help = "metabolite color file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
make_option("--cp", default = "", type = "character", help = "compare info "),
make_option("--pc", default = "", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))
source(str_c(scriptPath, "/parse_config.R"))

data <- read_csv("Class_Count.csv") %>%
    rename(percent = `Percentage(%)`) %>%
    mutate(rate = percent / 100, label = str_c(Class, "(",Count," , ", percent, "%)"))

data

colorData <- read_tsv(opt$mc) %>%
    select(c("Class", "col")) %>%
    rbind(c("Others", "#999999"))

head(colorData)

plotData <- data %>%
left_join(colorData, by = c("Class"))

head(plotData)

opar <- par(no.readonly = TRUE)
charN <- plotData$label %>%
nchar() %>%
max

defaultWidth <- charN * 0.08 + 7

finalWidth <- getFinalWidth(width, defaultWidth, opt$pc)

finalWidth

pdf("Class_Count_Pieplot.pdf", width = finalWidth, height = height)
par(mar = c(0.5, 0, 0.5, 0) + 0.1, family = "Times")

main <- if (!is.na(mainTitle)) {
  mainTitle
} else ""

pie(plotData$percent, labels = plotData$label, clockwise = TRUE, radius = 0.9, col = plotData$col,
border = "white", init.angle = 0, main = main)
par(opar)

dev.off()
